#!/bin/bash

#
# Copyright (C) 2012 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

packager=""
retcode=0
if [[ "$OSTYPE" == "darwin"* ]]
then
    packager="macports"

    if ! which port >& /dev/null
    then
        echo "Missing port binary, please install from http://www.macports.org/" >& 2
    fi
elif [[ "$OSTYPE" == "linux-gnu" ]] && which apt-get >& /dev/null
then
    packager="apt-get"
fi

function packager_install
{
    if [[ $packager == "macports" ]]
    then
        echo "sudo port install $1"
    elif [[ $packager == "apt-get" ]]
    then
        echo "sudo apt-get install $1"
    else
        echo "<your package manager> install $1"
    fi
}

function binary_check()
{
    local bin=$1
    local macports=$2
    local aptget=$3

    local pkg=""

    if type -f "$bin" >& /dev/null
    then
        return 0
    fi

    if [[ $packager == "macports" ]]
    then
        pkg="$macports"
    elif [[ $packager == "apt-get" ]]
    then
        pkg="$aptget"
    fi

    if [[ -n $pkg ]]
    then
        echo "Missing $bin binary; please install with '$(packager_install $pkg)'"
    fi

    retcode=1
    return 1
}

function python_check()
{
    local mod=$1
    local macports=$2
    local aptget=$3

    local pkg=""

    if python -c "import $mod" >& /dev/null
    then
        return 0
    fi

    if [[ $packager == "macports" ]]
    then
        pkg="$macports"
    elif [[ $packager == "apt-get" ]]
    then
        pkg="$aptget"
    fi

    if [[ -n $pkg ]]
    then
        echo "Missing python module $mod, please install with '$(packager_install $pkg)'"
    fi

    retcode=1
    return 1
}

binary_check xmllint libxml2 libxml2-utils
binary_check tidy tidy tidy
binary_check python python27 python2.7
python_check bs4 py27-beautifulsoup4 python-bs4
python_check mako py27-mako python-mako

exit $retcode

